<?php
declare (strict_types=1);

namespace app\admin\controller;

use addons\Builder\facade\Builder;
use app\common\model\ProductCate;
use think\facade\View;
use think\Response;
use think\response\Json;

class Product extends Base
{

    protected string $pk = 'id';

    protected string $model = '\app\common\model\Product';

    protected array $hasOne = ['cate1', 'cate2'];

    protected string $validate = 'Product';

    public array $tape = [
        ['field' => 'icon', 'title' => '图片', 'type' => 'icon'],
        ['field' => 'price', 'title' => '原价'],
        ['field' => 'vip_price', 'title' => '会员价'],
        ['field' => 'stock', 'title' => '库存', 'type' => 'stock']
    ];

    public function index(): string
    {

        return Builder::Table()
            ->autoStructure($this->model, $this->pk, 'barDemo,120')
            ->addTopButtons(['add', 'deleteAll'])
            ->addRightButtons(['edit'])
            ->addLineStyle('height: 65px;')
            ->addSearch([
                ['title', '输入商品名称/描述', 'input,Like'],
                ['cate_1,cate_2', '一级分类,二级分类', 'linkage', url('productCate/getCate')->build()]
            ], false)
            ->fetch();
    }


    public static function getCate(): array
    {
        return ProductCate::where('pid', 0)->field('id,title')->with('child')->select()->toArray();
    }

    public function add($tpl = '')
    {
        View::assign('cate', self::getCate());
        View::assign('tape', $this->tape);
        return parent::add('product/edit'); // TODO: Change the autogenerated stub
    }

    public function edit($id = '', $tpl = '', $info = '')
    {
        View::assign('cate', self::getCate());
        View::assign('tape', $this->tape);
        return parent::edit($id, 'product/edit', $info); // TODO: Change the autogenerated stub
    }

    public function save($param = [], $model = true): Json
    {
        $param = $this->request->post();
        $param['tape'] = $this->tape;
        return parent::save($param, $model); // TODO: Change the autogenerated stub
    }

    /**
     * 原点 2021年7月27日14:46:29 公共删除方法
     */
    public function delete(): Response
    {
        try {
            $param = $this->request->post();
            return json($this->model::productDelete($param, $this->getLogsArguments($param)));
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

}
